#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#define COMMAND_VALUESIZE 100
#define SSID "AI200"
#define PASSWORD "hanweiai"

// 辅助函数：执行 shell 命令并返回状态
int run_command(const char *cmd) {
    printf("Executing: %s\n", cmd);
    int ret = system(cmd);
    if (ret == -1) {
        perror("system() failed");
    }
    return ret;
}

void *wlan_test(void *argv) {
    // 1. 确保 wlan0 接口启用
    if (run_command("ip link set wlan0 up") != 0) {
        printf("Failed to bring up wlan0.\n");
        return (void *)-1;
    }

    // 2. 停止可能冲突的服务（如 NetworkManager）
    run_command("systemctl stop NetworkManager 2>/dev/null");
    run_command("killall wpa_supplicant dhclient 2>/dev/null");

    // 3. 生成 wpa_supplicant 配置
    FILE *wpa_conf = fopen("/tmp/wpa.conf", "w");
    if (!wpa_conf) {
        perror("fopen /tmp/wpa.conf");
        return (void *)-1;
    }
    fprintf(wpa_conf, "ctrl_interface=/var/run/wpa_supplicant\n");
    fprintf(wpa_conf, "update_config=1\n");
    fprintf(wpa_conf, "network={\n");
    fprintf(wpa_conf, "    ssid=\"%s\"\n", SSID);
    fprintf(wpa_conf, "    psk=\"%s\"\n", PASSWORD);
    fprintf(wpa_conf, "}\n");
    fclose(wpa_conf);

    // 4. 启动 wpa_supplicant（绑定到 wlan0）
    if (run_command("wpa_supplicant -B -D nl80211 -i wlan0 -c /tmp/wpa.conf") != 0) {
        printf("Failed to start wpa_supplicant.\n");
        return (void *)-1;
    }

    sleep(2);

    // 5. 获取 IP（通过 dhclient 或 udhcpc）
    printf("Requesting IP via DHCP on wlan0...\n");
    // 尝试 dhclient（常见于 Debian/Ubuntu）
    int dhcp_status = run_command("timeout 10 dhclient -v wlan0");
    if (dhcp_status != 0) {
        // 备用：尝试 udhcpc（常见于 BusyBox 系统）
        dhcp_status = run_command("timeout 10 udhcpc -i wlan0");
    }
    if (dhcp_status != 0) {
        printf("Failed to obtain IP address on wlan0.\n");
        return (void *)-1;
    }

    sleep(2);

    // 6. 验证 IP 是否分配到 wlan0
    printf("Checking IP on wlan0:\n");
    run_command("ip addr show wlan0");

    // 7. Ping 测试（指定 wlan0）
    printf("Testing connectivity...\n");
    if (run_command("ping -I wlan0 -c 3 -w 5 192.168.1.1") != 0) {
        printf("Ping failed. WIFI test failed.\n");
        return (void *)-1;
    }

    printf("WIFI test successful on wlan0!\n");
    return 0;
}

int main(int argc, char *argv[]) {
    printf("WiFi test on wlan0 (direct mode) starting...\n");

    int ret = (int)wlan_test(NULL);
    int err_code = (ret != 0) ? -1 : 0;

    if (err_code) {
        printf("WiFi 测试失败\n");
        system("echo \"$(date)：WiFi测试失败\" >> /userfs/all.txt");
    } else {
        printf("WiFi 测试成功\n");
        system("echo \"$(date)：WiFi测试成功\" >> /userfs/all.txt");
    }

    // 清理（可选）
    system("killall wpa_supplicant dhclient udhcpc 2>/dev/null");
    return 0;
}